﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SMS.Business.Stocks;
using SMS.DAL.Providers;
using SMS.Business;
using SMS.DAL;
using SMS.Business.Customer;
using SMS.Business.Items;

namespace SMS.Orders
{
    public partial class NewBuyingOrder : System.Web.UI.Page
    {
        SMS.DAL.User CurrentUser
        {
            get
            {
                return (SMS.DAL.User)Session["CurrentUser"];
            }
            set
            {
                Session["CurrentUser"] = value;
            }
        }
        public List<OrderItem> OrderItemsSource
        {
            set
            {
                if ((List<OrderItem>)Session["OrderItemsList"] == null)
                    Session["OrderItemsList"] = new List<OrderItem>();
                else
                    Session["OrderItemsList"] = value;
            }
            get
            {
                if ((List<OrderItem>)Session["OrderItemsList"] == null)
                    return new List<OrderItem>();
                else
                    return (List<OrderItem>)Session["OrderItemsList"];
            }
        }
        decimal? Total
        {
            set
            {
                ViewState["Total"] = value;
            }
            get
            {
                return (decimal)ViewState["Total"];
            }
        }

        OrderBusiness orderBus;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                OrderItemsSource = new List<OrderItem>();
                this.FillddlStocks();
            }
        }

        protected void txtBarCode_TextChanged(object sender, EventArgs e)
        {
            int stockid = int.Parse(ddlStocks.SelectedValue);
            StockItem stockItem = new StockItem();
            orderBus = new OrderBusiness();
            Item item = new Item();
            ItemProvider itemProv = new ItemProvider();
            ItemSearchCriteria itemSearch = new ItemSearchCriteria()
            {
                Barcode = txtBarCode.Text,
                Mark = txtMark.Text,
                 Name = txtItemName.Text
            };
            item = itemProv.Search(itemSearch).FirstOrDefault();
            stockItem = orderBus.GetStockItemByBarCode(txtBarCode.Text, stockid);
            if (stockItem != null)
            {
                this.txtBarCode.Text = string.Empty;
                this.ManageInserting(stockItem);
            }
            else
            {
                txtItemName.Text = item.Name;
                txtMark.Text = item.Mark;
            }
        }

        protected void txtMark_TextChanged(object sender, EventArgs e)
        {
            StockItem stockItem = new StockItem();
            if (txtBarCode.Text == string.Empty)
            {
                orderBus = new OrderBusiness();
                stockItem = orderBus.GetStockItemByItemNameAndItemMark(txtItemName.Text, txtMark.Text,
                        int.Parse(ddlStocks.SelectedValue));
                if (stockItem != null)
                {
                    txtItemName.Text = string.Empty;
                    txtMark.Text = string.Empty;
                    this.ManageInserting(stockItem);
                }
            }
            else
            {
                ItemBusiness itemBus = new ItemBusiness();
                ItemSearchCriteria itemSearch = new ItemSearchCriteria()
                {
                    Barcode = txtBarCode.Text,
                    Mark = txtBarCode.Text,
                    Name = txtMark.Text
                };
                Item IsExisted = new Item();
                IsExisted = itemBus.Search(itemSearch).FirstOrDefault();
                if (IsExisted == null)
                {
                    IsExisted = new Item()
                    {
                        BarCode = txtBarCode.Text,
                        ManfCountry = string.Empty,
                        Mark = txtMark.Text,
                        Name = txtItemName.Text,
                        SellingPrice = 0,
                    };
                    stockItem.Item = IsExisted;
                    stockItem.Count = 0;
                    stockItem.MinCount = 0;
                    stockItem.StockID = int.Parse(ddlStocks.SelectedValue);
                }
                itemBus.Insert(IsExisted, stockItem);
                ManageInserting(stockItem);
            }
        }

        private void ManageInserting(StockItem stockItem)
        {
            Total = 0;

            OrderItem orderItem = new OrderItem()
            {
                ItemCount = 1,
                StockItem = stockItem,
                UnitPrice = stockItem.Item.SellingPrice
            };


            if (OrderItemsSource.Count > 0)
            {
                for (int i = 0; i < OrderItemsSource.Count; i++)
                {
                    if (OrderItemsSource[i].StockItem.ID == stockItem.ID)
                    {
                        OrderItemsSource[i].ItemCount++;
                        this.BindDlStockItems();
                        return;
                    }
                }
                OrderItemsSource.Add(orderItem);
                this.BindDlStockItems();
            }
            else
            {
                OrderItemsSource.Add(orderItem);
                this.BindDlStockItems();
            }
        }

        private void FillddlStocks()
        {
            StocksBusiness StockBus = new StocksBusiness();

            StockUserSearchCriteria stockSearch = new StockUserSearchCriteria()
            {
                UserID = CurrentUser.ID
            };

            ddlStocks.DataSource = StockBus.GetByUserID(stockSearch);
            ddlStocks.DataTextField = "Name";
            ddlStocks.DataValueField = "ID";
            ddlStocks.DataBind();
        }

        protected void dlStockItems_EditCommand(object source, DataListCommandEventArgs e)
        {
            dlStockItems.EditItemIndex = e.Item.ItemIndex;
            this.BindDlStockItems();
        }

        private void BindDlStockItems()
        {
            dlStockItems.DataSource = OrderItemsSource;
            dlStockItems.DataBind();

            decimal? totalPerItem = 0;
            OrderItem item = new OrderItem();
            for (int i = 0; i < OrderItemsSource.Count; i++)
            {
                item = OrderItemsSource[i];
                Label lblTotalPerItem = (Label)dlStockItems.Items[i].FindControl("lblItemTotal");
                if (lblTotalPerItem != null)
                {
                    totalPerItem = item.ItemCount * item.UnitPrice;
                    lblTotalPerItem.Text = totalPerItem.ToString();
                }
            }
        }

        protected void dlStockItems_ItemCommand(object source, DataListCommandEventArgs e)
        {
        }

        protected void dlStockItems_CancelCommand(object source, DataListCommandEventArgs e)
        {
            dlStockItems.EditItemIndex = -1;
            this.BindDlStockItems();
        }

        protected void dlStockItems_UpdateCommand(object source, DataListCommandEventArgs e)
        {
            TextBox txtQuantity = (TextBox)e.Item.FindControl("txtQuantity");
            TextBox txtUnitPrice = (TextBox)e.Item.FindControl("txtSellingPrice");
            int quantity = int.Parse(txtQuantity.Text);
            decimal unitPrice = decimal.Parse(txtUnitPrice.Text);
            OrderItemsSource[e.Item.ItemIndex].UnitPrice = unitPrice;
            OrderItemsSource[e.Item.ItemIndex].StockItem.Item.SellingPrice = unitPrice;
            OrderItemsSource[e.Item.ItemIndex].ItemCount = quantity;
            dlStockItems.EditItemIndex = -1;
            BindDlStockItems();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            #region Insert Order
            CustomerBussiness customerBus = new CustomerBussiness();
            orderBus = new OrderBusiness();
            CustomerSearchCriteria customerSearch = new CustomerSearchCriteria()
            {
                Name = txtCustomer.Text
            };
            Customer customer = customerBus.Search(customerSearch).FirstOrDefault();

            StockUserSearchCriteria StockUserSearch = new StockUserSearchCriteria()
            {
                StockID = int.Parse(ddlStocks.SelectedValue),
                UserID = CurrentUser.ID
            };

            StockUser stockUser = orderBus.GetUserStockByUserIDandStockID(StockUserSearch);

            Order order = new Order()
            {
                Date = DateTime.Now,
                DiscountAmount = 0,
                PaidPrice = decimal.Parse(txtPaid.Text),
                TotalPrice = Total,
                StockUserID = stockUser.ID,
                CustomerID = customer.ID,
                Type = 1
            };

            int orderID = orderBus.InsertOrder(order);
            #endregion

            #region Insert Order Items

            OrderItemsBussiness orderItemBus = new OrderItemsBussiness();
            foreach (var item in OrderItemsSource)
            {
                item.OrderID = orderID;
                orderItemBus.Insert(item);
            }

            #region Reset Page
            OrderItemsSource.RemoveRange(0,OrderItemsSource.Count);
            txtPaid.Text = "0.0";
            lblChange.Text = "0.0";
            this.BindDlStockItems();
            #endregion

            #endregion

        }

        protected void dlStockItems_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Label lblTotal = (Label)e.Item.FindControl("lblTotal");
                Total = 0;
                foreach (var item in OrderItemsSource)
                {
                    Total += (item.ItemCount * item.UnitPrice);
                }
                lblTotal.Text = Total.ToString();
            }
        }

        protected void dlStockItems_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            OrderItemsSource.RemoveAt(e.Item.ItemIndex);
            this.BindDlStockItems();
        }

        protected void txtPaid_TextChanged(object sender, EventArgs e)
        {
            if (vldexpPaid.IsValid)
            {
                decimal paid = decimal.Parse(txtPaid.Text);
                decimal? change = 0;
                change = Total - paid;
                lblChange.Text = change.ToString();
            }
        }
    }
}